package cn.darkfire.web.Utils;


import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class SQLUtils {
    private static final SQLUtils instance = new SQLUtils();
    private Connection connection = null;
    private static String url = "jdbc:mysql://localhost:3306/sy3?useUnicode=true&characterEncoding=utf-8";
    private static String driver = "com.mysql.jdbc.Driver";
    private static String user = "root";
    private static String password = "123456";


    //静态方法块,类加载则会执行 且只执行一次
    static {
        InputStream in = SQLUtils.class.getClassLoader().getResourceAsStream("src/config/db.properties");
        Properties properties = new Properties();
        try{
            properties.load(in);
            url = properties.getProperty("url");
            driver = properties.getProperty("driver");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
        }catch (Exception e){

        }

    }

    //创建命令执行
    public Connection CreateConnection(){
        if(connection != null){return connection;}
        try{
            Class.forName(driver); //注册驱动
            Connection connection = DriverManager.getConnection(url,user,password);
            //此处建议使用 PreparedStatement 预处理SQL,可以有效防止SQL注入,更安全,且效率高,一次编译多次执行,可读性高,可维护性高
            //Mybatis 中尽量使用 #{} 预处理SQL 用`${}`动态拼接表名
            this.connection = connection;
            return this.connection;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public void close(ResultSet set,Statement statement, Connection connection) throws Exception{
            if(set!=null){set.close();}
            if(statement!=null){statement.close();}
            if(connection!=null){connection.close();}
    }

    public void close(ResultSet set, PreparedStatement preparedStatement, Connection connection){
        try{
            if(set!=null){set.close();}
            if(preparedStatement!=null){preparedStatement.close();}
            if(connection!=null){connection.close();}
        }catch (Exception e){

        }
    }

    public static SQLUtils getInstance() {
        return instance;
    }
}
